<?php
session_start();

if (!isset($_SESSION['username'])) {
    header("Location: ../login.html");
    exit();
}

include 'config.php';

if ($_SERVER["REQUEST_METHOD"] == "GET") {
    if (isset($_GET['apiurl']) && isset($_GET['pid']) && isset($_GET['key'])) {
        $apiurl = $_GET['apiurl'];
        $pid = $_GET['pid'];
        $key = $_GET['key'];
        $id = "1";

        // 数据验证
        if (empty($apiurl) || empty($pid) || empty($key)) {
            echo json_encode(["code" => 400, "msg" => "所有字段都是必填项"], JSON_UNESCAPED_UNICODE);
            exit();
        }

        // 准备更新语句
        $stmt = $conn->prepare("REPLACE INTO epay (id, api, pid, miyao) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("isss", $id, $apiurl, $pid, $key);

        if ($stmt->execute()) {
            echo json_encode(["code" => 200, "msg" => "配置信息更新成功"], JSON_UNESCAPED_UNICODE);
        } else {
            echo json_encode(["code" => 500, "msg" => "更新失败: " . $stmt->error], JSON_UNESCAPED_UNICODE);
        }
    } else {
        $id = "1";
        $stmt = $conn->prepare("SELECT apiurl, pid, key FROM epay WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            echo json_encode([
                "code" => 200,
                "msg" => "查询成功",
                "data" => [
                    "apiurl" => $row['apiurl'],
                    "pid" => $row['pid'],
                    "key" => $row['key']
                ]
            ], JSON_UNESCAPED_UNICODE);
        } else {
            echo json_encode(["code" => 404, "msg" => "未找到配置信息"], JSON_UNESCAPED_UNICODE);
        }
    }
} else {
    header("HTTP/1.1 405 Method Not Allowed");
    echo json_encode(["code" => 405, "msg" => "仅支持 GET 请求"], JSON_UNESCAPED_UNICODE);
}

$conn->close();
?>
